package com.jintoufs.weixin.hotel;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jintoufs.domain.collect.Collect;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.constants.MessageConstants;
import com.jintoufs.domain.contacts.Contacts;
import com.jintoufs.domain.coupon.Coupon;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.customer.CustomerCoupon;
import com.jintoufs.domain.features.Features;
import com.jintoufs.domain.hotel.HotelOrder;
import com.jintoufs.domain.hotel.HotelOrderDetail;
import com.jintoufs.domain.hotel.HotelPrice;
import com.jintoufs.domain.hotel.HotelRoom;
import com.jintoufs.domain.images.Images;
import com.jintoufs.interceptor.ParamCheck;
import com.jintoufs.service.banner.BannerService;
import com.jintoufs.service.collect.CollectService;
import com.jintoufs.service.contacts.ContactsService;
import com.jintoufs.service.coupon.CouponService;
import com.jintoufs.service.customer.CustomerCouponService;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.features.FeaturesService;
import com.jintoufs.service.hotel.HotelOrderService;
import com.jintoufs.service.hotel.HotelRoomService;
import com.jintoufs.service.hotel.HotelService;
import com.jintoufs.service.image.ImageService;
import com.jintoufs.util.date.DateUtils;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.weixin.SupportAction;
import io.swagger.annotations.Api;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(value = "酒店相关接口", description = "酒店相关接口")
@RestController
@RequestMapping("/api/hotel")
public class HotelAction extends SupportAction {
@Resource
private CustomerCouponService customerCouponService;
    @Resource
    private ContactsService contactsService;
    @Resource
    private HotelService hotelService;

    @Resource
    private HotelRoomService hotelRoomService;

    @Resource
    private CouponService couponService;

    @Resource
    private ImageService imageService;
    @Resource
    private HotelOrderService hotelOrderService;

    @Resource
    private FeaturesService featuresService;
    @Resource
    private CustomerService customerService;
    @Resource
    private CollectService collectService;
    @Resource
    private BannerService bannerService;

    @GetMapping("/index")
    @ResponseBody
    public AjaxMsg index(String regionName,Integer pageSize,Integer pageNum) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Map<String, Object> result = new HashMap<>();
            Map<String, Object> map = new HashMap();
            map.put("typeId", Constants.BANNER_TYPE_HOTEL);
            List<Map<String, Object>> banners = bannerService.queryByParams(map);

            //获取首页推荐
            Map<String, Object> param = new HashMap<>();
            param.put("status",Constants.RES_STATUS_NORMAL);param.put("inUse",Constants.RES_STATUS_NORMAL);
            param.put("regionName", regionName);
            param.put("pageStart",(pageNum-1)*pageSize);
            param.put("pageSize", pageSize);
            List<Map<String,Object>> hotels = hotelService.queryByParams(param);

            //获取酒店总数
            Integer totalCount = hotelService.getTotalCount();

            result.put("banner", banners);
            result.put("hotelList", hotels);
            result.put("totalCount", totalCount);
            ajaxMsg.setDatas(result);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setMessage("error");
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }

    @GetMapping("/moreRecommend")
    public AjaxMsg getMoreRecommend(String regionName,Integer pageSize,Integer pageNum,String isOtherCity) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        //获取首页推荐
        Map<String, Object> param = new HashMap<>();
        param.put("status",Constants.RES_STATUS_NORMAL);
        param.put("inUse",Constants.RES_STATUS_NORMAL);
        if(!ValidUtil.isEmpty(isOtherCity)&&"1".equals(isOtherCity)){
            param.put("isOtherCity",isOtherCity);
            param.put("otherCity",regionName);
        }else{
            param.put("regionName", regionName);
        }
        param.put("pageStart",(pageNum-1)*pageSize);
        param.put("pageSize", pageSize);
        List<Map<String,Object>> hotels = hotelService.queryByParams(param);
        ajaxMsg.setDatas(hotels);
        return ajaxMsg;
    }


    /**
     *
     * @param regionName 目的地
     * @param pageSize 分页大小
     * @param pageNum 当前页
     * @param startDate 入住时间
     * @param endDate 离开时间
     * @param orderType 排序类型，（price--价格排序,default-- 综合排序,other--其他)
     * @param isDesc (如果orderType为price,则根据这个字段判断升降序)
     * @param category （orderType为other时，查询条件加入分类）
     * @param keyWord （关键字，酒店名称模糊)
     * @return
     */
    @ParamCheck(params = "regionName")
    @GetMapping("/list")
    public AjaxMsg getHotels(String regionName,Integer pageSize,
                             Integer pageNum,String startDate,String endDate,
                             String orderType,String isDesc,String category,String keyWord,
                             String level,String isOtherCity) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String,Object> params = new HashMap<>();
        if (!ValidUtil.isEmpty(isOtherCity) && "1".equals(isOtherCity)) {
            params.put("otherCity", regionName);
        }else{
            params.put("regionName", regionName);
        }
//        try {
//           regionName= java.net.URLDecoder.decode(regionName, "ISO-8859-1");
//            //  regionName=new String(regionName.getBytes("ISO-8859-1"),"utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

        if (!ValidUtil.isEmpty(keyWord)) {
            params.put("keyWord","%"+keyWord+"%");
        }
        if (!ValidUtil.isEmpty(level)) {
            params.put("level","%"+level+"%");
        }
        if (!ValidUtil.isEmpty(startDate)){
            params.put("startDate",startDate);
        }else {
            params.put("startDate", DateUtils.getDate("yyyy-MM-dd"));
        }
        if (!ValidUtil.isEmpty(endDate)){
            params.put("endDate",endDate);
        }else {
            params.put("endDate",DateUtils.getTomorrowDate("yyyy-MM-dd"));
        }
        params.put("status",Constants.RES_STATUS_NORMAL);
        params.put("inUse",Constants.RES_STATUS_NORMAL);

        //放入分页
        Integer pageStart = (pageNum - 1) * pageSize;
        params.put("pageStart", pageStart);
        params.put("pageSize", pageSize);
        //判断是否是价格排序
        if (Constants.ORDER_PRICE.equals(orderType.trim())) {
            params.put("priceOrder", "price");
            if ("desc".equals(isDesc)) {
                params.put("isDesc", "desc");
            }
        }
        try {
            List<Map<String,Object>> hotels = hotelService.selectByParams(params);
            ajaxMsg.setDatas(hotels);
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            return ajaxMsg;
        }
        return ajaxMsg;
    }


    /**
     * 更具酒店Id带回去详细信息
     * @param id
     * @return
     */


    @GetMapping("/detail")
    public AjaxMsg getHotelDetail(String id,String startDate,String endDate){
        Map<String,Object> param = new HashMap<>();
        Map<String,Object> result = new HashMap<>();
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {

            //酒店基础信息
            param.put("id",id);
            List<Map<String,Object>> hotels = hotelService.queryByParams(param);
            if(!hotels.isEmpty()){
                result.put("hotel",hotels.get(0));
            }

            //酒店房间信息
            param.clear();
            param.put("hotelId",id);
            param.put("startDate",startDate);
            param.put("endDate",endDate);
            List<Map<String,Object>> hotelRooms = hotelRoomService.queryByParams(param);
            result.put("hotelRooms",hotelRooms);

            //酒店图片信息
            param.clear();
            param.put("valueId",id);
            List<Images> images = imageService.selectByparams(param);
            List<String> imagesList = new ArrayList<>();
            for (Images image : images) {
                String url = image.getPath();
                imagesList.add(url);
            }
            result.put("images", imagesList);
            //使用同样的参数查询特色信息
            List<Features> features = featuresService.selectByParams(param);
            result.put("features",features);
            ajaxMsg.setDatas(result);
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(Constants.SYSTEM_ERROR);
        }
        return ajaxMsg;
    }


    /**
     * 收藏一个酒店
     * @param hotelId
     * @param token
     * @return
     */
    @PostMapping(value = "/collect")
    public AjaxMsg collectScene(String hotelId,String token){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Collect collect = new Collect();
            Customer customer  = customerService.getByToken(token);
            collect.setCustomerId(customer.getId().toString());


            //TODO chenq 收藏，获取收藏类型
            collect.setTypeId(123);
            collect.setValueId(hotelId);
            collect.setAddTime(new Date());
            collectService.collect(collect);
            //返回保存的收藏
            ajaxMsg.setDatas(collect);

        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(e.getMessage());
            return ajaxMsg;
        }

        return ajaxMsg;
    }


    @GetMapping(value = "/orders")
    public AjaxMsg createOrder(String token, String id,String couponId,String userInfo,
                               String remark,Integer number,String startDate,
                               String endDate,Integer dates) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        HotelOrder hotelOrder = new HotelOrder();
        Map<String,Object> param = new HashMap<>();
        Map<String,Object> result = new HashMap<>();
        HotelOrderDetail hotelOrderDetail = new HotelOrderDetail();
        BigDecimal price = new BigDecimal("0.00");
        BigDecimal retailPrice = new BigDecimal("0");
        Customer customer = getCustomerByToken(token);
        try{
            if (ValidUtil.isEmpty(customer)) {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setDatas(Constants.NOAUTH);
                return ajaxMsg;
            }

            //校验房间状态
            Map paramRoomPrice = new HashMap();
            paramRoomPrice.put("id",id);
            paramRoomPrice.put("startTime",startDate);
            paramRoomPrice.put("endTime",endDate);
            List<Map> hotelRoomPrice = hotelRoomService.queryPriceByParams(paramRoomPrice);
            boolean flag = false;
            for (int i=0;i<hotelRoomPrice.size()-1;i++) {
                Map m = hotelRoomPrice.get(i);
                if (!ValidUtil.isEmpty(m.get("status")) && "0".equals(m.get("status").toString())) {
                    flag = true;
                    break;
                } else if (ValidUtil.isEmpty(m.get("status"))) {
                    flag = true;
                    break;
                }
            }
            if(flag){
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                Map gf = new HashMap();
                gf.put("status", 0);//关房
                ajaxMsg.setDatas(gf);
                return ajaxMsg;
            }
            if (customer!=null){
                param.put("customerId",customer.getId());
                param.put("couponId",couponId);
                List<CustomerCoupon> customerCoupons = customerCouponService.queryByParam(param);
                if (valid(customerCoupons,!ValidUtil.isEmpty(couponId))){
                    HotelRoom hotelRoom = hotelRoomService.queryById(id);
                    Integer minReserve = hotelRoomService.getMinReserve(id,startDate,endDate);
                    if (minReserve>=number){
                        HotelPrice hotelPrice = null;
                        for (int i = 0;i<dates;i++){
                            Date date = DateUtils.parseDate(DateUtils.formatAddDate(startDate,"yyyy-MM-dd",i),"yyyy-MM-dd");
                            param.put("date",date);
                            param.put("hotelRoomId",id);
                            List<HotelPrice> hotelPrices = hotelRoomService.getHotelPrice(param);
                            if (hotelPrices.size()!=0){
                                hotelPrice = hotelPrices.get(0);
                                hotelPrice.setReserve(hotelPrice.getReserve()-number);
                                //更新库存
                                hotelRoomService.updateReserve(hotelPrice);
                            }else {
                                hotelPrice = new HotelPrice();
                                hotelPrice.setReserve(hotelRoom.getNumber()-number);
                                hotelPrice.setDate(date);
                                hotelPrice.setHotelId(hotelRoom.getHotelId());
                                hotelPrice.setPrice(hotelRoom.getPrice());
                                hotelPrice.setRetailPrice(hotelRoom.getRetailPrice());
                                hotelPrice.setHotelRoomId(hotelRoom.getId());
                                hotelPrice.setId(getUUID());
                                hotelRoomService.savePrice(hotelPrice);
                            }
                            price = price.add(hotelPrice.getPrice().multiply(new BigDecimal(String.valueOf(number))));
                            retailPrice = retailPrice.add(hotelPrice.getRetailPrice().multiply(new BigDecimal(String.valueOf(number))));
                        }
                        hotelOrder.setCustomerId(customer.getId());
                        hotelOrder.setRecommendId(customer.getRecommendId());
                        hotelOrder.setSpreadId(customer.getSpreadId());
                        hotelOrder.setHotelId(hotelRoom.getHotelId());
                        hotelOrder.setModifyTime(new Date());
                        hotelOrder.setRemark(remark);
                        result.put("price",price);
                        //优惠前价格
                        hotelOrder.setActPrice(price);
                        if (!ValidUtil.isEmpty(couponId)){
                            hotelOrder.setCustomerCouponId(customerCoupons.get(0).getId());
                            BigDecimal couponPrice = couponService.getById(customerCoupons.get(0).getCouponId()).getMinAmount();
                            if (price.compareTo(couponPrice)>0){
                                price = price.subtract(couponPrice);
                            }
                        }

                        //放入状态未支付
                        hotelOrder.setStatus(Constants.ORDER_STATUS_UNPAY);
                        //订单创建时间
                        hotelOrder.setInTime(new Date());
                        //优惠后价格
                        hotelOrder.setPrice(price);
                        //放入订单分销价
                        hotelOrder.setSharePrice(retailPrice);
                        hotelOrder.setId(getUUID());
                        hotelOrderService.save(hotelOrder);
                        List<Map> userInfoList = JSONArray.parseArray(userInfo,Map.class);
                        Map user = userInfoList.get(0);
                        StringBuilder sb = new StringBuilder();
                        for(int i=0;i<userInfoList.size();i++){
                            Map con = userInfoList.get(i);
                            if(i==userInfoList.size()-1){
                                sb.append(userInfoList.get(i).get("name").toString());
                            }else{
                                sb.append(userInfoList.get(i).get("name").toString()).append(",");
                            }
                            Contacts contacts = new Contacts();
                            if(!ValidUtil.isEmpty(con.get("idCard"))){
                                contacts.setIdCard(con.get("idCard").toString());
                            }
                            if(!ValidUtil.isEmpty(con.get("name"))){
                                contacts.setName(con.get("name").toString());
                            }
                            if(!ValidUtil.isEmpty(con.get("tel"))){
                                contacts.setTelephone(con.get("tel").toString());
                            }
                            contacts.setUserId(customer.getId());

                            param.put("name",contacts.getName());
                            List<Contacts> contactsList = contactsService.selectByParam(param);
                            if (contactsList.isEmpty()){
                                contactsService.save(contacts,getUUID());
                            }
                        }

                        hotelOrderDetail.setId(getUUID());
                        hotelOrderDetail.setIdcard(user.get("idCard").toString());
                        hotelOrderDetail.setRealName(sb.toString());
                        hotelOrderDetail.setHotelRoomId(id);
                        hotelOrderDetail.setTelephone(user.get("tel").toString());
                        hotelOrderDetail.setCheckInTime(DateUtils.parseDate(startDate,"yyyy-MM-dd"));
                        hotelOrderDetail.setCheckOutTime(DateUtils.parseDate(endDate,"yyyy-MM-dd"));
                        hotelOrderDetail.setHotelOrderId(hotelOrder.getId());
                        hotelOrderDetail.setNumber(number);
                        hotelOrderDetail.setPrice(price);
                        hotelOrderService.saveDetail(hotelOrderDetail,getUUID());
                    } else {
                        ajaxMsg.setCode(AjaxMsg.FAILURE);
                        ajaxMsg.setMessage("您选择的日期中有一天没有房间。");
                    }
                }else {
                    ajaxMsg.setCode(AjaxMsg.FAILURE);
                    ajaxMsg.setMessage("优惠券无效。");
                }
            }else {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("身份验证失败，请重新登陆");
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setMessage(MessageConstants.SYSTEM_ERROR_MESSAGE);
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            return ajaxMsg;
        }
        ajaxMsg.setDatas(hotelOrder);
        return ajaxMsg;
    }

    @GetMapping("/room")
    private AjaxMsg room(String id,String startDate,String endDate){
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String,Object> result = new HashMap<>();

        Map<String,Object> param = new HashMap<>();
        param.put("id",id);
        param.put("startTime",startDate);
        param.put("endTime",endDate);
        List<Map<String,Object>> hotelRoom = hotelRoomService.queryByParams(param);
        param.clear();
        param.put("valueId",id);
        List<Images> imagesList = imageService.selectByparams(param);
        List<String> imagesPathList = new ArrayList<>();
        for (Images images : imagesList) {
            imagesPathList.add(images.getPath());
        }
        result.put("room",hotelRoom.get(0));
        result.put("images",imagesPathList);
        ajaxMsg.setDatas(result);

        return ajaxMsg;
    }

    @GetMapping("/roomPrice")
    private AjaxMsg roomPrice(String id,String startDate,String endDate){
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String,Object> param = new HashMap<>(1);
        try{
            param.put("id",id);
            param.put("startTime",startDate);
            param.put("endTime",endDate);
            List<Map<String,Object>> hotelRoom = hotelRoomService.queryPriceByParams(param);
            ajaxMsg.setDatas(hotelRoom);
        }catch (Exception e){
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("获取价格失败");
        }
        return ajaxMsg;
    }

    private boolean valid(List<CustomerCoupon> list,boolean use){
        if (use){
            if (list.size()!=0){
                CustomerCoupon customerCoupon = list.get(0);
                if (customerCoupon.getUsedTime()==null){
                    Coupon coupon = couponService.getById(customerCoupon.getCouponId());
                    Date now = new Date();
                    return coupon.getSendStartDate().before(now) && coupon.getSendEndDate().after(now)&&Constants.COUPON_TYPE_HOTEL.equals(coupon.getTypeId());
                }
            }
            return false;
        }else {
            return true;
        }
    }


}
